<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;


/**
 * vue商城
 *入库管理
 * @icon fa fa-user
 */
class Storage extends Backend
{
    protected $relationSearch = true;
    protected $ProductModel = null;
    protected $SupplierModel = null;
    protected $DepotProductModel = null;
    protected $BackModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Depot.Storage');
        $this->ProductModel = model('Product.Product');
        $this->SupplierModel = model('Depot.Supplier');
        $this->BackModel = model('Depot.Back');
        $this->DepotProductModel = model('Depot.Storage.Product');
        $status = [
            '0' => '待审批',
            '1' => '审批失败',
            '2' => '待入库',
            '3' => '入库完成'
        ];
        $this->view->assign(["typeList" => $this->model->getTypeList(), 'status' => $status]);
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('supplier')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('supplier')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            // 接收添加的商品数据，json字符串转成数组
            $productList = json_decode($params['product'], true);

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();
            $type=isset($params['type']) ? $params['type'] :'1';
            // 封装入库数据
            $StorageData = [
                'code' => build_code('SU'),
                'supplierid' => $params['supplierid'],
                'type' => $type,
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => 0
            ];

            $StorageStatus = $this->model->validate('common/Depot/storage/Storage')->save($StorageData);

            if ($StorageStatus === FALSE) {
                $this->error($this->model->getError());
                exit;
            }

            // 存放封装好的商品数据
            $ProductData = [];

            foreach ($productList as $item) {
                $ProductData[] = [
                    'storageid' => $this->model->id,
                    'proid' => $item['id'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];
            }

            // 验证数据
            $ProductStatus = $this->DepotProductModel->validate('common/Depot/storage/Product')->saveAll($ProductData);

            if ($ProductStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
            }

            // 大判断
            if ($ProductStatus === FALSE || $StorageStatus === FALSE) {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error(__('添加失败'));
            } else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success();
            }
        }

        return $this->view->fetch();
    }
    /**
     * 详情
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->with(['admin', 'reviewer'])->find($ids);
        $supplier = $this->SupplierModel->with(['provinces', 'citys', 'districts'])->where('id', $row['supplierid'])->find();

        $ProductList = $this->DepotProductModel->where('storageid', $row['id'])->select();

        $productData = [];

        foreach ($ProductList as $item) {
            $product = model('Product.Product')->with(['type', 'unit'])->find($item['proid']);

            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];;
        }

        $data = [
            'row' => $row,
            'supplier' => $supplier,
            'productData' => $productData
        ];
        return $this->view->fetch('', $data);
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        // 相当于find($ids)
        $row = $this->model->get($ids);
        // 找不到数据返回错误信息
        if (!$row) {
            $this->error(__('该入库单不存在，请重新选择'));
        }
        $ProductList = $this->DepotProductModel->where('storageid', $row['id'])->select();
        $supplier = $this->SupplierModel->with(['provinces', 'citys', 'districts'])->where('id', $row['supplierid'])->find();
        if ($supplier) {

            if (!$supplier) {
                $this->error(__('该供应商不存在，请重新选择'));
            }
        } else {
            // 查询退货订单信息
            $back = $this->BackModel->with(['business'])->where(['storageid' => $row['id']])->find();

            if (!$back) {
                $this->error('退货单不存在');
            }
        }

        if (!$ProductList) {
            $this->error(__('该商品不存在，请重新选择'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');

            // 接收添加的商品数据，json字符串转成数组
            $productList = json_decode($params['product'], true);

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();

            // 封装入库数据
            $StorageData = [
                'id' => $row['id'],
                'type' => $params['type'],
                'supplierid' => $params['supplierid'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => $row['status'],
            ];

            if ($row['type'] == 1) {
                $StorageData['supplierid'] = $params['supplierid'];
            }

            // 如果等于true说明直销入库
            if ($supplier) {
                $StorageStatus = $this->model->validate('common/Depot/storage/Storage.edit')->isUpdate(true)->save($StorageData);
            } else {
                $StorageStatus = $this->model->validate('common/Depot/storage/Storage.back_edit')->isUpdate(true)->save($StorageData);
            }

            if ($StorageStatus === FALSE) {
                $this->error($this->model->getError());
                exit;
            }

            // 存放封装好的商品数据
            $ProductData = [];

            // 封装一个在修改时新增的商品
            $NewProData = [];

            foreach ($productList as $item) {
                if (isset($item['id'])) {
                    $ProductData[] = [
                        'id' => $item['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                } else {
                    $NewProData[] = [
                        'storageid' => $row['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }
            }

            $delproid = json_decode($params['delproid']);

            // 删除不需要的商品
            if (!empty($delproid)) {
                $DelStatus = $this->DepotProductModel->destroy($delproid);

                if ($DelStatus === FALSE) {
                    $this->model->rollback();
                    $this->error($this->DepotProductModel->getError());
                }
            }

            $NewProStatus = $this->DepotProductModel->validate('common/Depot/storage/Product')->saveAll($NewProData);

            // 验证数据
            $ProductStatus = $this->DepotProductModel->validate('common/Depot/storage/Product.edit')->isUpdate(true)->saveAll($ProductData);
            if ($ProductStatus === FALSE || $NewProStatus === FALSE) {
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
            }

            // 大判断
            if ($ProductStatus === FALSE || $StorageStatus === FALSE || $NewProStatus === FALSE) {
                $this->model->rollback();
                $this->DepotProductModel->rollback();
                $this->error(__('修改失败'));
            } else {
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success();
            }
        }

        // 商品的数据
        $productData = [];

        foreach ($ProductList as $item) {
            $product = model('Product.Product')->with(['type', 'unit'])->find($item['proid']);

            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];;
        }

        // 赋值
        $data = [
            'row' => $row,
            'supplier' => $supplier
        ];

        // 如果等于false说明这个退货入库
        if (!$supplier) {
            $data['back'] = $back;
        }

        // 返回js使用的数据
        $this->assignconfig('Product', ['productData' => $productData]);

        return $this->view->fetch('', $data);
    }
    /*
    审核
    */
    public function process($ids = NULL)
    {
        $status = $this->request->param('status', '', 'trim');
        if ($status == '') {
            $this->error(__('参数不能为空'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('入库数据不存在'));
        }
        $data = ['id' => $ids, 'reviewerid' => $this->auth->id];
        if ($status == 1) {
            $data['status'] = '2';
        } else {
            $data['status'] = '1';
        }
        $result = $this->model->isUpdate()->save($data);
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success("操作成功");
    }
    /**
     * 撤回审核
     */
    public function cancel($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('入库数据不存在'));
        }
        $data = ['id' => $ids, 'status' => '0', 'reviewerid' => null];
        $result = $this->model->isUpdate()->save($data);
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success("操作成功");
    }
    /**
     * 入库
     */
    public function storage($ids)
    {
        $row = $this->model->with(['admin', 'reviewer'])->find($ids);
        $ProductList = $this->DepotProductModel->where('storageid', $row['id'])->select();
        // 商品的数据
        $productData = [];

        foreach ($ProductList as $item) {
            $product = model('Product.Product')->find($item['proid']);
            $stock = bcadd($product['stock'], $item['nums']);
            $productData[] = [
                'id' => $item['proid'],
                'stock' => $stock,
            ];;
        }
        // 开启事务
        $this->model->startTrans();
        $this->ProductModel->startTrans();
        $Status = $this->model->isUpdate()->save(['id' => $ids, 'status' => '3', 'adminid' => $this->auth->id]);
        if ($Status === false) {
            $this->error(__('入库失败'));
        }
        $ProductStatus = $this->ProductModel->isUpdate()->saveAll($productData);
        if ($ProductStatus === false) {
            $this->model->rollback();
            $this->error(__('入库失败'));
        }
        $this->model->commit();
        $this->ProductModel->commit();
        $this->success(__('入库成功'));
    }
    /**
     * 软删除
     */
    public function del($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('入库数据不存在'));
        }
        $result = $this->model->destroy($ids);
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success("操作成功");
    }
    /**
     * 商品
     */
    public function product()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->ProductModel
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];


            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 供货商
     */
    public function supplier()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        // 判断是否有Ajax请求
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $list = $this->SupplierModel
                ->with('region')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = ['total' => $list->total(), 'rows' => $list->items()];


            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 入库回收站首页
     */
    public function recyclebin()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with('supplier')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->onlyTrashed()
                ->with('supplier')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }
    /**
     * 入库回收站还原
     */
    public function restore($ids=null){
        $row = $this->model->onlyTrashed()->select($ids);
        if (empty($row)) {
            $this->error('当前入库数据不存在');
        }
        $res=$this->model->onlyTrashed()->where('id','IN',$ids)->update(['deletetime'=>null]);
         if($res==0){
                $this->error($this->model->getError());
        }
       $this->success();
    }
    /**
     * 入库回收站删除
     */
    public function destroy($ids=null){
        $res=$this->model->destroy($ids,true);
         if($res==0){
                $this->error($this->model->getError());
        }
       $this->success('删除成功');
    }
}
